package com.dqhl.stable.activity;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationListener;
import com.dqhl.stable.R;
import com.dqhl.stable.base.BaseActivity;
import com.dqhl.stable.listener.LightListener;
import com.dqhl.stable.listener.ShakeListener;
import com.dqhl.stable.util.Config;
import com.dqhl.stable.util.Constant;
import com.dqhl.stable.util.DeviceUtils;
import com.dqhl.stable.util.Dlog;
import com.dqhl.stable.util.JPushUtil;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

public class MainActivity extends BaseActivity implements View.OnClickListener {

    private boolean quit = false; //设置退出标识
    private AMapLocationClient aMapLocationClient = null;
    private double curLongitude; //当前经度
    private double curLatitude; //当前纬度

    private ShakeListener shakeListener; //摇晃手机的监听
    private LightListener lightListener; //光照感应的监听
    private MessageReceiver mMessageReceiver;

    private TextView tv_alias;
    //    private Button btn_jpush;
    private Button btn_set_alias;
    private EditText et_alias;
    private TextView tv_light_result;
    private TextView tv_have_light;
    private TextView tv_location;
    private Button btn_start_location;
    private EditText et_shake_num;
    private Button btn_set_shake;
    private TextView tv_shake_num;
    private TextView tv_light_num;
    private EditText et_light_num;
    private Button btn_set_light;
    private EditText et_seconds;
    private Button btn_set_seconds;

    private String spAlias = "";
    private int shakeNum = 3000;
    private float lightNum = 2000;
    private int seconds = 15;
    private boolean isProject = true;
    private TextView tv_version;
    private TextView tv_seconds;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
        initAMap();
        initShakeSensor();
        initLightSensor();
        registerMessageReceiver();
    }

    private void registerMessageReceiver() {
        mMessageReceiver = new MessageReceiver();
        IntentFilter filter = new IntentFilter();
        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
        filter.addAction(Constant.MESSAGE_RECEIVED_ACTION);
        registerReceiver(mMessageReceiver, filter);
    }

    class MessageReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (Constant.MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
                String messge = intent.getStringExtra(Constant.KEY_MESSAGE);
                String extras = intent.getStringExtra(Constant.KEY_EXTRAS);
                StringBuilder showMsg = new StringBuilder();
                showMsg.append(Constant.KEY_MESSAGE + " : " + messge + "\n");
                if (!JPushUtil.isEmpty(extras)) {
                    showMsg.append(Constant.KEY_EXTRAS + " : " + extras + "\n");
                }
                // TODO 如果收到消息为某个值，就执行一个操作
                Dlog.e("收到推送msg为:" + messge);
                if ("2".equals(messge)) { //如果值为 2，停止监听
                    if (shakeListener != null) {
                        shakeListener.stop();
                    }
                    if (lightListener != null) {
                        lightListener.stop();
                    }
                    isProject = false;
                    Dlog.e("收到推送msg为:2-----stop----Listener");
                } else if ("1".equals(messge)) { //如果值为 1，开启监听
                    shakeListener.start();
                    lightListener.start();
                    isProject = true;
                    Dlog.e("收到推送msg为:1-----tart----Listener");
                }
            }
        }
    }

    private void initView() {
        tv_alias = (TextView) findViewById(R.id.tv_alias);
//        btn_jpush = (Button) findViewById(R.id.btn_jpush);
        btn_set_alias = (Button) findViewById(R.id.btn_set_alias);
        et_alias = (EditText) findViewById(R.id.et_alias);
        tv_light_result = (TextView) findViewById(R.id.tv_light_result);
        tv_have_light = (TextView) findViewById(R.id.tv_have_light);
        tv_location = (TextView) findViewById(R.id.tv_location);
        btn_start_location = (Button) findViewById(R.id.btn_start_location);
        et_shake_num = (EditText) findViewById(R.id.et_shake_num);
        btn_set_shake = (Button) findViewById(R.id.btn_set_shake);
        tv_shake_num = (TextView) findViewById(R.id.tv_shake_num);
        tv_light_num = (TextView) findViewById(R.id.tv_light_num);
        et_light_num = (EditText) findViewById(R.id.et_light_num);
        btn_set_light = (Button) findViewById(R.id.btn_set_light);
        et_seconds = (EditText) findViewById(R.id.et_seconds);
        btn_set_seconds = (Button) findViewById(R.id.btn_set_seconds);
        tv_seconds = (TextView) findViewById(R.id.tv_seconds);
        tv_version = (TextView) findViewById(R.id.tv_version);
        String strVersion = "当前版本:v" + DeviceUtils.getVersion(this);
        tv_version.setText(strVersion);

//        btn_jpush.setOnClickListener(this);
        btn_set_alias.setOnClickListener(this);
        btn_start_location.setOnClickListener(this);
        btn_set_shake.setOnClickListener(this);
        btn_set_light.setOnClickListener(this);
        btn_set_seconds.setOnClickListener(this);

        seconds = sp.getInt(Constant.SECONDES, 15);
        Dlog.e("init-----seconds:" + seconds);
        if (0 == seconds) {
            toast("请先设置时间间隔");
        } else {
            tv_seconds.setText("时间间隔:" + seconds);
        }

        spAlias = sp.getString(Constant.ALIAS, "");
        Dlog.e("init-----alias:" + spAlias);
        if (TextUtils.isEmpty(spAlias)) {
            toast("请先设置alias");
            tv_alias.setText("请先设置alias");
        } else {
            tv_alias.setText("alias为:" + spAlias);
        }
        shakeNum = sp.getInt(Constant.SHAKE, 3000);
        Dlog.e("init-----shakeNum:" + shakeNum);
        if (0 == shakeNum) {
            toast("请先设置摇晃灵敏度");
            tv_shake_num.setText("先设置摇晃度");
        } else {
            tv_shake_num.setText("摇晃度:" + shakeNum);
        }
        lightNum = sp.getFloat(Constant.LIGHT, 2000);
        Dlog.e("init-----lightNum:" + lightNum);
        if (0 == lightNum) {
            toast("请先设置光照灵敏度");
            tv_light_num.setText("先光照度");
        } else {
            tv_light_num.setText("光照度:" + lightNum);
        }

    }

    /**
     * 初始化地图
     */
    private void initAMap() {
        aMapLocationClient = app.getaMapLocationClient();
        aMapLocationClient.setLocationListener(mLocationListener);
    }

    AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            if (aMapLocation != null && aMapLocation.getErrorCode() == 0) {
                //解析定位结果
//                String result = AMapUtils.getLocationStr(aMapLocation);
                curLongitude = aMapLocation.getLongitude();
                curLatitude = aMapLocation.getLatitude();
//                shakeListener.start();
//                lightListener.start();
                Dlog.e("定位成功_经纬度：" + curLongitude + "," + curLatitude);
                tv_location.setText("定位成功_经纬度：" + curLongitude + "," + curLatitude);
            } else {
                String errText = "定位失败," + aMapLocation.getErrorCode() + ": " + aMapLocation.getErrorInfo();
                Dlog.e("AmapErr:" + errText);
                tv_location.setText("定位失败");
            }
        }
    };

    final Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            // 在此处添加执行的代码
            if (isProject) {
                shakeListener.start();
                lightListener.start();
                Dlog.e("重新开启:shakeListener");
                Dlog.e("重新开启:lightListener");
            }

        }
    };
//    handler.removeCallbacks(this);// 关闭定时器处理

    /**
     * 初始化摇晃手机
     */
    private void initShakeSensor() {
        shakeListener = new ShakeListener(this, shakeNum);
        Dlog.e("MainActivity....onCreate....shakeListener_start..");

        shakeListener.setOnShakeListener(new ShakeListener.OnShakeListener() {
            @Override
            public void onShake() {

                // 震动（测试用）
//                Vibrator vibrator = (Vibrator) getSystemService(Service.VIBRATOR_SERVICE);
//                vibrator.vibrate(300);
                shakeListener.stop();
                Dlog.e("after...shake........shakeListener_stop..");
                // 向服务器发送警报
                sendShakeMsg2Server();
                if (isProject) {
                    handler.postDelayed(runnable, seconds * 1000);// 延时时长
                }
            }
        });

    }

    /**
     * 光照感应
     */
    private void initLightSensor() {
        lightListener = new LightListener(this);
        lightListener.setOnLightListener(new LightListener.onLightListener() {
            @Override
            public void onLight(float acc, float lux) {
                String result = "精度acc:" + acc + ";" + "光线强度lux：" + lux;
                tv_light_result.setText(result);
//                Dlog.e(result);
                if (lux > lightNum) {
                    tv_have_light.setText("有光照");
                    // 震动（测试用）
//                    Vibrator vibrator = (Vibrator) getSystemService(Service.VIBRATOR_SERVICE);
//                    vibrator.vibrate(300);
                    lightListener.stop();
                    Dlog.e("after...light........LightListener_stop..");
                    //向服务器发送警报
                    sendLightMsg2Server();
                    if (isProject) {
                        handler.postDelayed(runnable, seconds * 1000);// 延时时长
                    }
                } else {
                    tv_have_light.setText("");
                }
            }
        });
    }

    /**
     * 有震动时向服务器发送消息
     * 箱子号case_sign='2';状态码case_state='2';箱子坐标case_point='23.123,32.213123'
     */
    private void sendShakeMsg2Server() {
        String alias = sp.getString(Constant.ALIAS, "");
        if (TextUtils.isEmpty(alias)) {
            toast("请先设置alias");
        } else {
            toast("箱子号:" + alias);
            String case_point = curLongitude + "," + curLatitude; //箱子的坐标
            Dlog.e("有震动时...箱子的坐标:" + case_point + ";箱子号:" + alias);
            RequestParams params = new RequestParams(Config.Api.warning);
            params.addBodyParameter("case_state", "2"); //箱子的状态
            params.addBodyParameter("case_sign", alias); //箱子号
            params.addBodyParameter("case_point", case_point); //箱子的坐标
            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    Dlog.e(result);
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {

                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {

                }
            });
        }
    }

    /**
     * 有光照时向服务器发送消息
     */
    private void sendLightMsg2Server() {
        String alias = sp.getString(Constant.ALIAS, "");
        if (TextUtils.isEmpty(alias)) {
            toast("请先设置alias");
        } else {
            toast("箱子号:" + alias);
            String case_point = curLongitude + "," + curLatitude; //箱子的坐标
            Dlog.e("有光照时...箱子的坐标:" + case_point + ";箱子号:" + alias);
            RequestParams params = new RequestParams(Config.Api.warning);
            params.addBodyParameter("case_state", "4"); //箱子的状态
            params.addBodyParameter("case_sign", alias); //箱子号
            params.addBodyParameter("case_point", case_point); //箱子的坐标
            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    Dlog.e(result);
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {

                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {

                }
            });
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
//            case R.id.btn_jpush:
//                overlay(JPushMainActivity.class);
//                break;
            case R.id.btn_set_alias: //设置别名
                setAlias();
                break;
            case R.id.btn_start_location:
                startLocation();
                break;
            case R.id.btn_set_shake:
                setShakeNum();
                break;
            case R.id.btn_set_light:
                setLightNum();
                break;
            case R.id.btn_set_seconds:
                setSeconds();
                break;
        }
    }

    private void setSeconds() {
        String strSeconds = et_seconds.getText().toString().trim();
        if (!TextUtils.isEmpty(strSeconds)) {
            seconds = Integer.parseInt(strSeconds);
            sp.edit().putInt(Constant.SECONDES, seconds).apply();
            tv_seconds.setText("时间间隔:" + seconds);
            toast("设置成功");
//            initShakeSensor();
//            initLightSensor();
        }
    }

    private void setLightNum() {
        String strLight = et_light_num.getText().toString().trim();
        if (!TextUtils.isEmpty(strLight)){
            lightNum = Float.parseFloat(strLight);
            sp.edit().putFloat(Constant.LIGHT, lightNum).apply();
            tv_light_num.setText("光照度:" + lightNum);
            toast("光照度设置成功");
//            initLightSensor();
        }

    }

    private void setShakeNum() {
        String strShake = et_shake_num.getText().toString().trim();
        if (!TextUtils.isEmpty(strShake)){
            shakeNum = Integer.parseInt(strShake);
            sp.edit().putInt(Constant.SHAKE, shakeNum).apply();
            tv_shake_num.setText("摇晃度:" + shakeNum);
            toast("摇晃度设置成功");
//            initShakeSensor();
        }
    }

    private void startLocation() {
        tv_location.setText("重新开始定位");
        aMapLocationClient.setLocationListener(mLocationListener);
        aMapLocationClient.startLocation();
    }

    /**
     * JPush设置别名
     */
    private void setAlias() {
        String alias = et_alias.getText().toString().trim();
        if (TextUtils.isEmpty(alias)) {
            toast(R.string.error_alias_empty);
            return;
        }
        if (!JPushUtil.isValidTagAndAlias(alias)) {
            toast(R.string.error_tag_gs_empty);
            return;
        }

        //调用JPush API设置Alias
        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, alias));
    }

    private static final int MSG_SET_ALIAS = 1001;

    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_ALIAS:
                    Dlog.e("Set alias in handler.");
                    JPushInterface.setAliasAndTags(getApplicationContext(), (String) msg.obj, null, mAliasCallback);
                    break;
                default:
                    Dlog.e("Unhandled msg - " + msg.what);
            }
        }
    };

    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {

        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    sp.edit().putString(Constant.ALIAS, alias).apply();
                    tv_alias.setText("alias为:" + alias);
                    Dlog.e(logs + "---alias为:" + alias);
                    break;

                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    Dlog.e(logs);
                    if (JPushUtil.isConnected(getApplicationContext())) {
                        mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60);
                    } else {
                        Dlog.e("No network");
                    }
                    break;

                default:
                    logs = "Failed with errorCode = " + code;
                    Dlog.e(logs);
            }
            toast(logs);
        }

    };

    @Override
    protected void onPause() {
        if (shakeListener != null) {
            shakeListener.stop();
        }
        if (lightListener != null) {
            lightListener.stop();
        }
        super.onPause();
    }

    @Override
    protected void onResume() {
        aMapLocationClient.startLocation();
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        if (shakeListener != null) {
            shakeListener.stop();
        }
        if (lightListener != null) {
            lightListener.stop();
        }
        if (aMapLocationClient != null) {
            aMapLocationClient.stopLocation();
            aMapLocationClient.onDestroy();
        }
        aMapLocationClient = null;
        if (mMessageReceiver != null) {
            unregisterReceiver(mMessageReceiver);
        }
        Dlog.e("shakeListener___stop");
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        if (!quit) { //询问退出程序
            toast("再按一次退出程序");
            new Timer(true).schedule(new TimerTask() { //启动定时任务
                @Override
                public void run() {
                    quit = false; //重置退出标识
                }
            }, 2000); //2秒后运行run()方法
            quit = true;
        } else { //确认退出程序
            super.onBackPressed();
            finish();
        }
    }
}
